package com.dfd.store.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.dfd.store.domain.Category;
import com.dfd.store.domain.Order;
import com.dfd.store.domain.PageModel;
import com.dfd.store.domain.Product;
import com.dfd.store.domain.User;
import com.dfd.store.service.CategoryService;
import com.dfd.store.service.OrderService;
import com.dfd.store.service.ProductService;
import com.dfd.store.service.impl.CategoryServiceImpl;
import com.dfd.store.service.impl.OrderServiceImpl;
import com.dfd.store.service.impl.ProductServiceImpl;
import com.dfd.store.utils.UUIDUtils;
import com.dfd.store.utils.UploadUtils;
import com.dfd.store.web.base.BaseServlet;

import net.sf.json.JSONArray;

public class AdminProductServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	public String findAll(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		int num = Integer.parseInt(req.getParameter("num"));
		ProductService productService = new ProductServiceImpl();
		PageModel pageModel = productService.findAll(num);
		req.setAttribute("page", pageModel);
		return "/admin/product/list.jsp";
	}

	public String findDown(HttpServletRequest req, HttpServletResponse resp) throws Exception {

		int num = Integer.parseInt(req.getParameter("num"));
		ProductService productService = new ProductServiceImpl();
		PageModel pageModel = productService.findDown(num);
		req.setAttribute("page", pageModel);
		return "/admin/product/pushDown_list.jsp";
	}

	public String UpProduct(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String pid = req.getParameter("pid");
		ProductService productService = new ProductServiceImpl();
		productService.UpProduct(pid);
		resp.sendRedirect(req.getContextPath() + "/AdminProductServlet?method=findDown&num=1");
		return null;
	}

	public String DownProductByid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String pid = req.getParameter("pid");
		ProductService productService = new ProductServiceImpl();
		productService.DownProductByid(pid);
		resp.sendRedirect(req.getContextPath() + "/AdminProductServlet?method=findAll&num=1");
		return null;
	}

	public String save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// 获取全部分类信息
		CategoryService categoryService = new CategoryServiceImpl();
		// 将全部分类信息放入req
		List<Category> allCats = categoryService.getAllCats();
		// 转发
		req.setAttribute("allCats", allCats);
		return "/admin/product/add.jsp";

	}

	public String addProduct(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// 创建磁盘文件项工厂
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		// 设置缓存区的大小:如果文件的大小超过了缓冲区的大小,就会产生临时文件
		diskFileItemFactory.setSizeThreshold(3 * 1024 * 1024);
		// 设置临时文件的存放路径
		// diskFileItemFactory.setRepository(repository);
		// 获得核心解析类
		ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
		// 解决中文文件名上传乱码
		fileUpload.setHeaderEncoding("UTF-8");
		// 设置单个文件的大小
		// fileUpload.setFileSizeMax(fileSizeMax);
		// 设置表单中所有文件项的文件总大小
		// fileUpload.setSizeMax(sizeMax);
		// 解析req返回list集合
		List<FileItem> list = fileUpload.parseRequest(req);
		// 获得每个部分
		// 将遍历的值存入一个map中
		Map map = new HashMap<>();
		String oldFileName = null;
		for (FileItem fileItem : list) {
			// 判断普通项和文件上传项
			if (fileItem.isFormField()) {
				// 普通项
				String name = fileItem.getFieldName();
				String value = fileItem.getString("UTF-8");
				System.out.println(name + "    " + value);
				map.put(name, value);
			} else {
				// 文件上传项
				// 获取原文件名
				// oldFileName = 111.png
				oldFileName = fileItem.getName();
				System.out.println("文件名:" + oldFileName);
				// newFileName=B9D444CFF0594BBDAFA194169AE94E4B.png
				String newFileName = UploadUtils.getUUIDName(oldFileName);
				// 获得文件的输入流
				InputStream iStream = fileItem.getInputStream();
				// 获取文件要上传的路径
				// realPath =
				// D:\Java\apache-tomcat-7.0.92\webapps\Store\products\1
				// String realPath =
				// this.getServletContext().getRealPath("/products/1/");
				//String realPath = "D:/Java/workspace/Store/WebContent/products/1/";
				String realPath = "C:/Java/workspace/eclipse 32/workspace/Store/WebContent/products/1/";
				// dir = /5/1
				String dir = UploadUtils.getDir(newFileName);
				// path =
				// D:\Java\apache-tomcat-7.0.92\webapps\Store\products\1/5/1
				String path = realPath + dir;
				// 创建一个目录
				// file=
				// D:\Java\apache-tomcat-7.0.92\webapps\Store\products\1\5\1
				File file = new File(path);
				if (!file.exists()) {
					file.mkdirs();
				}
				// 创建一个文件
				// file2 =
				// D:\Java\apache-tomcat-7.0.92\webapps\Store\products\1\5\1\B9D444CFF0594BBDAFA194169AE94E4B.png
				File file2 = new File(path, newFileName);
				if (!file2.exists()) {
					file2.createNewFile();
				}
				OutputStream oStream = new FileOutputStream(file2);
				// 将输入流的数据刷到输出流
				IOUtils.copy(iStream, oStream);
				// 释放资源
				IOUtils.closeQuietly(iStream);
				IOUtils.closeQuietly(oStream);
				map.put("pimage", "products/1" + dir + "/" + newFileName);
			}
		}
		// 创建一个Product对象
		Product product = new Product();
		// 封装数据
		BeanUtils.populate(product, map);
		product.setPid(UUIDUtils.getId());
		product.setPdate(new Date());
		product.setPflag(0);
		product.setPimage(map.get("pimage").toString());
		ProductService productService = new ProductServiceImpl();
		productService.addProduct(product);
		resp.sendRedirect(req.getContextPath() + "/AdminProductServlet?method=findAll&num=1");
		return null;

	}

	
}